package com.redhat.auth.domain.infra.hibernate;

import java.util.List;

import org.hibernate.FetchMode;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.dayatang.spring.repository.BaseEntityRepositoryHibernateSpring;
import com.redhat.auth.domain.Account;
import com.redhat.auth.domain.AccountRepository;
import com.redhat.auth.domain.Role;
/**
 * 
 * @author lingen.liu
 * Account 仓储的实现
 */
@Repository
public class AccountRepositoryImpl extends
		BaseEntityRepositoryHibernateSpring<Account, Long> implements AccountRepository {

	public AccountRepositoryImpl(){
		super(Account.class);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Account> queryAccountByRole(Role role) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Account.class);
		criteria.createAlias("roles", "rs");
		criteria.add(Restrictions.eq("rs.id", role.getId()));
		criteria.setFetchMode("roles", FetchMode.JOIN);
		List<Account> acountList = getHibernateTemplate().findByCriteria(criteria);
		return acountList;
	
	}

	@Override
	public boolean isEmailExist(String email) {
		Object account = getSingleResult("from Account a where a.email = ?", new Object[]{email});
	    if(account!=null)return true;
	    return false;
	}

	@Override
	public boolean isUsernameExist(String username) {
		Object account = getSingleResult("from Account a where a.username = ?", new Object[]{username});
	    if(account!=null)return true;
	    return false;
	}

	/**
	 * 根据用户的姓名获取用户信息,并且连同角色信息一同获取
	 */
	public Account get(String username) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Account.class);
		criteria.add(Restrictions.eq("username", username));
		criteria.setFetchMode("roles", FetchMode.JOIN);
		List<Account> acountList = getHibernateTemplate().findByCriteria(criteria);
		if(acountList.size()==0)return null;
		return acountList.get(0);
	}
}
